//
//  TLAVPlayer.m
//  TLAVPlayerDemo
//
//  Created by Tianlong on 2017/6/30.
//  Copyright © 2017年 Tianlong. All rights reserved.
//

#import "TLAVPlayer.h"
#import "TLAVPlayerBottomBar.h"
#import "TLAVPlayerSlider.h"
#import "TLLoadingView.h"
#import "Masonry.h"


@interface TLAVPlayer ()<TLAVPlayerBottomBarDelegate>

/**
 视频item信息
 */
//@property (nonatomic , strong) AVPlayerItem *playerItem;

/**
 加载视图
 */
@property (nonatomic , weak) TLLoadingView *loadingView;

/**
 记录上次的视频地址
 */
@property (nonatomic , copy) NSString *currentURL;

/**
 底部功能条
 */
@property (nonatomic , weak) TLAVPlayerBottomBar *bottomBar;

/**
 返回键
 */
@property (nonatomic , weak) UIButton *backBtn;

/**
 用来盛放播放器，并且做全屏半屏的逻辑
 */
@property (nonatomic , weak) UIView *containerView;

/**
 进度条是否停止了拖拽：这个标记用来解决松开拖拽进度条时，进度条来回跳的现象
 */
@property (nonatomic , assign) BOOL sliderEndDragging;

/**
 视频总时长
 */
@property (nonatomic , assign) float amountTime;

/**
 拖拽的时间
 */
@property (nonatomic , assign) float draggingTime;

/**
 记录当前的bottomBar是否是隐藏的
 */
@property (nonatomic , assign) BOOL bottomBarHidden;

/**
 是否弹过提示框：如果弹出过，那么在就只在点击的时候在弹出提示，若允许了则下此点击不在提示
 */
@property (nonatomic , assign) BOOL isAlerted;

/**
 是否允许了使用流量播放
 */
@property (nonatomic , assign) BOOL allowPlayOnFlow;

/**
 状态栏的状态
 */
@property (nonatomic , assign) BOOL statusBarHidden;

/**
 截图用
 */
//@property (nonatomic , strong) AVPlayerItemVideoOutput *videoOutput;

/**
 当前的播放时间
 */
@property (nonatomic , assign) float currentPlayTime;

@end

@implementation TLAVPlayer

-(instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
        //创建容器视图
        [self addContainerView];
        //添加avplayerlayer
        [self addPlayerLayerView];
        //设置进度条
        [self addSlider];
        //添加封面图
        [self addCoverView];
        //添加加载视图
        [self addLoadingView];
        //添加返回键
        [self addBackBtn];
        
        //默认自动播放
        self.autoPlay = YES;
        self.sliderEndDragging = YES;
        self.bottomBarHidden = NO;
        self.isAlerted = NO;
        self.allowPlayOnFlow = NO;
        self.resetVideoURL = YES;
        
        self.bottomBar.alpha = 0;
        [self hiddenBottomBar];
        
        self.containerView.backgroundColor = [UIColor clearColor];
        self.coverView.backgroundColor = [UIColor clearColor];
        self.coverView.coverV.backgroundColor = [UIColor clearColor];
        self.coverView.backgroundColor = [UIColor clearColor];
        
        [self addNote];
    }
    return self;
}

#pragma mark - addNote 添加通知 和 手势
-(void)addNote{
    //监听播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(failedToPlayToEndTime:) name:AVPlayerItemFailedToPlayToEndTimeNotification object:self.player.currentItem];
    
    //给containerView添加点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [self.containerView addGestureRecognizer:tap];
    //监听设备在前后台的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appwillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}

#pragma mark - 创建容器视图
-(void)addContainerView{
    UIView *contV = [[UIView alloc] init];
    self.containerView = contV;
    [self addSubview:self.containerView];
    
    [self.containerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
}

#pragma mark - 半屏时，是否显示返回键
-(void)setShowBackBtnInSmallScreen:(BOOL)showBackBtnInSmallScreen{
    _showBackBtnInSmallScreen = showBackBtnInSmallScreen;
    self.backBtn.hidden = !showBackBtnInSmallScreen;
    self.backBtn.alpha = self.backBtn.hidden == YES ? 0 : 1;
}

#pragma mark - layoutSubviews
-(void)layoutSubviews{
    [super layoutSubviews];
    NSLog(@"self.frame =========== %@",NSStringFromCGRect(self.frame));
    self.playerLayer.frame = self.bounds;
}

#pragma mark - 点击播放器，隐藏或者显示底部工具条
-(void)tap:(UITapGestureRecognizer *)tap{
    
    self.bottomBarHidden = !self.bottomBarHidden;
    
    WS(ws);
    if (self.bottomBarHidden) {
        [UIView animateWithDuration:.5 animations:^{
            ws.backBtn.alpha = 0;
            ws.bottomBar.alpha = 0;
        }];
    }
    else{
        [self cancelBottomBarHidden];
        [UIView animateWithDuration:.5 animations:^{
            ws.backBtn.alpha = 1;
            ws.bottomBar.alpha = 1;
        }];
    }
}
-(void)hiddenBottomBar{
    WS(ws);
    [UIView animateWithDuration:.5 animations:^{
        ws.backBtn.alpha = 0;
        ws.bottomBar.alpha = 0;
    }completion:^(BOOL finished) {
        ws.bottomBarHidden = YES;
        if (ws.state == TLPlayerStatePlayFinished) {
            if (ws.showBackBtnInSmallScreen) {
                ws.backBtn.alpha = 1;
                ws.backBtn.hidden = NO;
            }
        }
    }];
}

-(void)showBottomBar{
    WS(ws);
    [UIView animateWithDuration:.5 animations:^{
        ws.backBtn.alpha = 1;
        ws.bottomBar.alpha = 1;
    }];
}
//点击slider上的播放按钮，拖拽进度条，点击全屏时，取消3秒的隐藏操作，3秒之后再隐藏
-(void)cancelBottomBarHidden{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hiddenBottomBar) object:nil];
    [self performSelector:@selector(hiddenBottomBar) withObject:nil afterDelay:5];
}

#pragma mark - setupBackBtn：设置返回键以及点击事件
-(void)addBackBtn{
    if (self.backBtn == nil) {
        UIButton *backBtn = [[UIButton alloc] init];
        self.backBtn = backBtn;
        [self.backBtn setImage:[UIImage imageNamed:@"playback"] forState:UIControlStateNormal];
        [self.backBtn addTarget:self action:@selector(clickedBackBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.containerView addSubview:self.backBtn];
        
        WS(ws);
        [self.backBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(ws.containerView);
            make.left.equalTo(ws.containerView);
            make.width.offset(50);
            make.height.offset(50);
        }];
    }
}

//点击返回键要做的事
-(void)clickedBackBtn{
    if (self.bottomBar.isFullScreen) {
        if (self.clickdeScreenBlock) {
            self.clickdeScreenBlock(NO);
        }
        [self smallScreen];
    }
    else{
        if (self.clickedBackBtnBlock) {
            self.clickedBackBtnBlock();
        }
        //pop出当前视图等
    }
}

#pragma mark - 设置进度条
-(void)addSlider{
    if (self.bottomBar == nil) {
        TLAVPlayerBottomBar *bottomBar = [[TLAVPlayerBottomBar alloc] init];
        self.bottomBar = bottomBar;
        self.bottomBar.delegate = self;
        [self.containerView addSubview:self.bottomBar];
        
        WS(ws);
        [self.bottomBar mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(ws.containerView.mas_left);
            make.right.equalTo(ws.containerView.mas_right);
            make.height.offset(40);
            make.bottom.equalTo(ws.containerView.mas_bottom);
        }];
    }
}

//拖拽bottomBar
-(void)playerBottomBar:(TLAVPlayerBottomBar *)bottomBar beiginDraggingForCurTime:(float)curTime{
    [self cancelBottomBarHidden];
}

-(void)playerBottomBar:(TLAVPlayerBottomBar *)bottomBar didDraggingForScale:(float)scale{
    [self cancelBottomBarHidden];
}

-(void)playerBottomBar:(TLAVPlayerBottomBar *)bottomBar endDraggingForCurTime:(float)curTime scale:(float)scale{
    self.sliderEndDragging = NO;
    //更改当前的播放时间
    float seekTime = self.amountTime*scale;
    [self.player seekToTime:CMTimeMake(seekTime, 1) toleranceBefore:CMTimeMake(1, 30) toleranceAfter:CMTimeMake(1, 30)];
    self.bottomBar.curTime = seekTime;
    self.draggingTime = seekTime;
    [self cancelBottomBarHidden];
}

//点击bottomBar全屏、半屏
-(void)playerBottomBar:(TLAVPlayerBottomBar *)bottomBar didClickedScreenBtn:(BOOL)isFullScreen{
    [self cancelBottomBarHidden];
    if (self.clickdeScreenBlock) {
        self.clickdeScreenBlock(isFullScreen);
    }
    //记录下状态栏的状态
    self.statusBarHidden = [UIApplication sharedApplication].statusBarHidden;
    isFullScreen == YES ? [self fullScreen] : [self smallScreen];
}

//点击bottomBar的播放按钮
-(void)playerBottomBar:(TLAVPlayerBottomBar *)bottomBar didClickedPlayBtn:(BOOL)playing{
    [self cancelBottomBarHidden];
    //由于playing状态是先改变后通知代理，所以NO对应暂停，YES对应播放
    playing == NO ? [self pause] : [self play];
}


#pragma mark - 设置封面图

-(void)addCoverView{
    if (self.coverView == nil) {
        TLCoverView *coverView = [[TLCoverView alloc] init];
        self.coverView = coverView;
        WS(ws);
        
        //点击封面
        [self.coverView setTapCoverView:^{
            [ws resume];
        }];
        
        //点击重播
        [self.coverView setReplayBlock:^{
            [ws replay];
        }];
        
        //点击分享
        [self.coverView setShareBlock:^{
            
        }];
        
        [self.containerView addSubview:self.coverView];
        [self.coverView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(ws.containerView.mas_top);
            make.left.equalTo(ws.containerView.mas_left);
            make.right.equalTo(ws.containerView.mas_right);
            make.bottom.equalTo(ws.containerView.mas_bottom);
        }];
    }
}

-(void)setCoverURL:(NSString *)coverURL{
    _coverURL = coverURL;
}

#pragma mark - 设置加载视图
-(void)addLoadingView{
    if (self.loadingView == nil) {
        TLLoadingView *loading = [[TLLoadingView alloc] init];
        self.loadingView = loading;
        self.loadingView.backgroundColor = [UIColor whiteColor];
        self.loadingView.hidden = YES;
        [self addSubview:self.loadingView];
        
        WS(ws);
        [self.loadingView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(ws.mas_top);
            make.left.equalTo(ws.mas_left);
            make.right.equalTo(ws.mas_right);
            make.bottom.equalTo(ws.mas_bottom);
        }];
    }
}
/** 开启loading */
-(void)startLoading{
    [self.loadingView startLoding];
    self.loadingView.hidden = NO;
    self.state = TLPlayerStateLoading;
}

/** 停止loading */
-(void)stopLoading{
    self.loadingView.hidden = YES;
    [self.loadingView stopLoading];
}


#pragma mark - playerLayer

/**
 添加播放器的layer
 */
-(void)addPlayerLayer{
    if (self.playerLayer == nil) {
        self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        self.playerLayer.backgroundColor = [UIColor clearColor].CGColor;
        self.playerLayer.videoGravity = AVLayerVideoGravityResize;//AVLayerVideoGravityResizeAspectFill
        [self.playerLayerView.layer addSublayer:self.playerLayer];
        [self layoutIfNeeded];
        self.playerLayer.frame = self.bounds;
        NSLog(@"重新创建AVPlayerLayer");
    }
}

/**
 移除播放器的layer
 */
-(void)removePlayerLayer{
    if(self.playerLayer != nil){
        [self.playerLayer removeFromSuperlayer];
        self.playerLayer = nil;
        NSLog(@"如果自己还有playerLayer删除自己的playerLayer");
    }
}

/**
 layer的容器
 */
-(void)addPlayerLayerView{
    if (self.playerLayerView == nil) {
        UIView *playerLayerView = [[UIView alloc] init];
        self.playerLayerView = playerLayerView;
        [self.containerView addSubview:self.playerLayerView];
        
        [self.playerLayerView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.left.bottom.right.offset(0);
        }];
    }
}


#pragma mark - avplayer lazy loading
//- (AVPlayer *)player{
//    
//    //if (!_player)
//    {
//        self.playerItem = [self getAVPlayItem];
//        _player = [AVPlayer playerWithPlayerItem:self.playerItem];
////        [self addProgressObserver];
////        [self addObserverToPlayerItem:self.playerItem];
//        
//        // 解决8.1系统播放无声音问题，8.0、9.0以上未发现此问题
//        AVAudioSession * session = [AVAudioSession sharedInstance];
//        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
//        [session setActive:YES error:nil];
//    }
//    return _player;
//}


- (AVPlayerItem *)getAVPlayItem{
    
    if (self.videoUrl==nil) {
        self.videoUrl = @"";//防止崩溃
    }
    NSAssert(self.videoUrl != nil, @"必须先传入视频url！！！");
    
    AVURLAsset *videoAsset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:self.videoUrl] options:nil];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:videoAsset];
    
//    //截图用：准备参数字典
//    NSDictionary *settings = @{(id)kCVPixelBufferPixelFormatTypeKey:
//                                   [NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
//                               };
//    //创建AVPlayerItemVideoOutput
//    self.videoOutput = [[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:settings];
//    //向playerItem添加AVPlayerItemVideoOutput
//    [playerItem addOutput:self.videoOutput];
//    [playerItem addOutput:[TLAVPlayerItemVideoOutput sharedTLAVPlayerItemVideoOutput]];
    return playerItem;
    
//    if ([self.videoUrl rangeOfString:@"http"].location != NSNotFound) {
//        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:[self.videoUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]]];
//        return playerItem;
//    }else{
//        AVAsset *movieAsset  = [[AVURLAsset alloc]initWithURL:[NSURL fileURLWithPath:self.videoUrl] options:nil];
//        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
//        return playerItem;
//    }
}


#pragma mark - 监听AVPlayerItem
-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem{
    //监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}

/**
 *  通过KVO监控播放器状态
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    //如果是切换页面了，不在继续播放
    if (self.state == TLPlayerStateStop) {
        //NSLog(@"停止任何后续操作 ---- %s",__FUNCTION__);
        return;
    }
    
    AVPlayerItem *playerItem = object;
    //视频总时长
    float isNaN = playerItem.duration.timescale;
    if (!isnan(isNaN)) {
        float videoDuration = playerItem.duration.value / isNaN;
        self.amountTime = videoDuration;
        self.bottomBar.amountTime = videoDuration;
    }
    
    //NSLog(@"视频总时长 = %f",videoDuration);
    
    if ([keyPath isEqualToString:@"status"]) {
        
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue];
        
        if(status == AVPlayerStatusReadyToPlay){
            
            self.state = TLPlayerStateReadyToPlay;
        }
        else if (status == AVPlayerStatusFailed){
            
            self.state = TLPlayerStateFailed;
        }
        else if (status == AVPlayerStatusUnknown){
            
            self.state = TLPlayerStateUnknown;
        }
    }
    else if([keyPath isEqualToString:@"loadedTimeRanges"]){
        
        NSArray *array = playerItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
        //初始时间
        //float startSeconds = CMTimeGetSeconds(timeRange.start);
        
        //已缓冲的时间
        float bufferTime = CMTimeGetSeconds(timeRange.duration);
        self.bottomBar.bufferTime = bufferTime;
        
        //缓冲的时间大于拖拽的时间改变标记
        if (bufferTime > self.draggingTime) {
            self.sliderEndDragging = YES;
        }
        
        if (self.state == TLPlayerStateReadyToPlay || self.state == TLPlayerStatePlayFinished) {
            if (self.beginTime > 0) {
                if(bufferTime > self.beginTime){
                    [self.player seekToTime:CMTimeMake(self.beginTime, 1) toleranceBefore:CMTimeMake(1, 30) toleranceAfter:CMTimeMake(1, 30)];
                    [self play];
                }
            }
            else{
                if (bufferTime > 0) {
                    [self play];
                }
            }
        }
    }
}

#pragma mark - 处理进度相关
-(void)addProgressObserver{
    
    WS(ws);
    [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(0.1f, NSEC_PER_SEC)  queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float currentPlayTime = CMTimeGetSeconds(time);
        ws.currentPlayTime = currentPlayTime;
        if(ws.sliderEndDragging){
            [ws.bottomBar setCurTime:currentPlayTime];
        }
    }];
}

#pragma mark - 设置URL
-(void)setVideoUrl:(NSString *)videoUrl{
    
    _videoUrl = videoUrl;
    
    if(!self.resetVideoURL){
        if ([self.currentURL isEqualToString:self.videoUrl]) {
            //同一个url不会重复设置
            return;
        }
    }
    self.state = TLPlayerStateChangedURL;
    self.currentURL = self.videoUrl;
    if (self.autoPlay) {
        [self resume];
    }
}

#pragma mark - 启动播放器，移除旧的监听，添加新的监听，更换播放资源item
-(void)resume{
    
    if (self.state != TLPlayerStatePlayFinished) {
        [self startLoading];
        
        //初始加载隐藏底部大进度条
        self.bottomBar.alpha = 0;
        [self hiddenBottomBar];
        
        //移除旧的监听
        [self.player.currentItem  removeObserver:self forKeyPath:@"status"];
        [self.player.currentItem  removeObserver:self forKeyPath:@"loadedTimeRanges"];
        
        //清除之前的playerlayer
        [self removePlayerLayer];
        self.player = [AVPlayer playerWithPlayerItem:[self getAVPlayItem]];
        [self addPlayerLayer];
        
        //添加新的监听
        [self addObserverToPlayerItem:self.player.currentItem];
        [self addProgressObserver];

    }
}

#pragma mark - 播放
-(void)play{
    
    [self.player play];

    [self addPlayerLayer];
    
    [self cancelBottomBarHidden];
    
    self.state = TLPlayerStatePlaying;
    
    //隐藏load视图,延后 .1 秒消失是为了解决：如果不延迟，从跳过片头的位置开始播放前会看到0秒时视频的画面
    WS(ws);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [ws stopLoading];
    });
}

#pragma mark - 暂停
-(void)pause{
    [self.player pause];
    [self cancelBottomBarHidden];
    self.state = TLPlayerStatePause;
}


#pragma mark - 播放完成
-(void)playFinished:(NSNotification *)note{
    
    AVPlayerItem *item = (AVPlayerItem *)note.object;
    
    if (item == self.player.currentItem) {
        self.state = TLPlayerStatePlayFinished;
        
        if (self.playFinished) {
            self.playFinished();
        }
        
        if (self.isFullScreen) {
            self.backBtn.alpha = 1;
            self.backBtn.hidden = NO;
        }
        else{
            if (self.showBackBtnInSmallScreen) {
                self.backBtn.alpha = 1;
                self.backBtn.hidden = NO;
            }
        }
    }
}

#pragma mark - failedToPlayToEndTime
- (void)failedToPlayToEndTime:(NSNotification *)note {
    NSLog(@"failedToPlayToEndTime = %@",note.userInfo);
}

#pragma mark - 重播
-(void)replay{
    if (self.beginTime > 0) {
        [self.player seekToTime:CMTimeMake(self.beginTime, 1) toleranceBefore:CMTimeMake(1, 30) toleranceAfter:CMTimeMake(1, 30)];
    }
    else{
        [self.player seekToTime:CMTimeMake(1, 1) toleranceBefore:CMTimeMake(0, 30) toleranceAfter:CMTimeMake(1, 30)];
    }
    [self play];
}

#pragma mark - 此方法适用于切换界面时，停止加载：暂停视频的播放，取消playerItem的加载
-(void)stop{
    
    if (self.state == TLPlayerStatePlayFinished){
        self.coverView.rePlayV.hidden = NO;
    }
    else{
        if (self.state == TLPlayerStatePlaying) {
            [self pause];
        }
        else{
            self.state = TLPlayerStateStop;
        }
        self.coverView.rePlayV.hidden = YES;
    }
}

#pragma mark - 销毁
-(void)destroy{
    [self stop];
    [self.player.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    [self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    [self removeFromSuperview];
    NSLog(@"-----%s",__FUNCTION__);
}

#pragma mark - 通知代理播放器状态更新了--TLPlayerViewDelegate
-(void)callDelegateWithState:(TLPlayerState)state{
    //通知代理播放器当前的状态
    if ([self.delegate respondsToSelector:@selector(player:playerStateDidChanged:)]) {
        [self.delegate player:self playerStateDidChanged:state];
    }
}

#pragma mark - 设置播放器的状态
-(void)setState:(TLPlayerState)state{
    _state = state;
    
    switch (state) {
            
        case TLPlayerStateChangedURL:
            //NSLog(@"播放自当前的状态：state == TLPlayerStateChangedURL");
            break;
            
        case TLPlayerStateLoading:
            self.coverView.playIconV.hidden = YES;
            //NSLog(@"播放自当前的状态：state == TLPlayerStateLoading");
            break;
            
        case TLPlayerStateReadyToPlay:
            //NSLog(@"播放自当前的状态：state == TLPlayerStateReadyToPlay");
            break;
            
        case TLPlayerStatePlaying:
            //只显示封面图播放按钮
            self.coverView.hidden = YES;
            self.bottomBar.playing = YES;
            self.coverView.rePlayV.hidden = YES;
            //NSLog(@"播放自当前的状态：state == TLPlayerStatePlaying");
            break;
            
        case TLPlayerStatePause:
            //只显示封面图播放按钮
            self.coverView.hidden = NO;
            self.coverView.playIconV.hidden = NO;
            self.coverView.rePlayV.hidden = YES;
            
            /*{
                __block UIImage *image = nil;
                self.coverView.coverV.image = nil;
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    image = [self getCoverImage];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (image != nil) {
                            self.coverView.coverV.image = image;
                        }
                    });
                });
             }
             */
            
            self.bottomBar.playing = NO;
            //NSLog(@"播放自当前的状态：state == TLPlayerStatePause");
            break;
            
        case TLPlayerStateStop:
            //[self.playerItem cancelPendingSeeks];
            //[self.playerItem.asset cancelLoading];
            [self stopLoading];
            //NSLog(@"播放自当前的状态：state == TLPlayerStateStop");
            break;
            
        case TLPlayerStatePlayFinished:
            //展示封面图的重播按钮
            self.coverView.hidden = NO;
            self.coverView.playIconV.hidden = YES;
            self.coverView.rePlayV.hidden = NO;
            self.bottomBar.playing = NO;
            //NSLog(@"播放自当前的状态：state == TLPlayerStatePlayFinished");
            break;
            
        case TLPlayerStateFailed:
            NSLog(@"播放自当前的状态：state == TLPlayerStateFailed");
            break;
            
        case TLPlayerStateUnknown:
            NSLog(@"播放自当前的状态：state == TLPlayerStateUnknown");
            break;
            
        default:
            break;
    }
    
    [self callDelegateWithState:self.state];
}

#pragma mark - 全屏
-(void)fullScreen{
    
    /** 此demo的逻辑，因项目而异 */
    [self forceToOrientation:UIDeviceOrientationLandscapeLeft];
    [DefaultWindow addSubview:self.containerView];
    self.containerView.frame = DefaultWindow.bounds;
    [self.containerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(DefaultWindow);
    }];
    [self layoutIfNeeded];
    [self setNeedsUpdateConstraints];
    
    /*本人项目中的逻辑
    [self forceToOrientation:UIDeviceOrientationLandscapeLeft];
    [[UIApplication sharedApplication] setStatusBarOrientation:UIDeviceOrientationLandscapeLeft];
    [DefaultWindow addSubview:self.containerView];
    [self.containerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(DefaultWindow.mas_centerX);
        make.centerY.equalTo(DefaultWindow.mas_centerY);
        make.width.equalTo(DefaultWindow.mas_height);
        make.height.equalTo(DefaultWindow.mas_width);
    }];
    
    WS(ws);
    [UIView animateWithDuration:.25 animations:^{
        ws.containerView.transform = CGAffineTransformMakeRotation(M_PI/2);
    }];
    */
    
    self.containerView.backgroundColor = [UIColor whiteColor];
    self.bottomBar.isFullScreen = YES;
    self.isFullScreen = YES;
    self.backBtn.hidden = NO;
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
}

#pragma mark - 半屏
-(void)smallScreen{
    
    /** 此demo的逻辑，因项目而异 */
    [self forceToOrientation:UIDeviceOrientationPortrait];
    [self addSubview:self.containerView];
    WS(ws);
    [self.containerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(ws.mas_top);
        make.left.equalTo(ws.mas_left);
        make.right.equalTo(ws.mas_right);
        make.bottom.equalTo(ws.mas_bottom);
    }];
    [self.playerLayerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(ws.containerView.mas_top);
        make.left.equalTo(ws.containerView.mas_left);
        make.right.equalTo(ws.containerView.mas_right);
        make.bottom.equalTo(ws.containerView.mas_bottom);
    }];
    
    /*本人项目中的逻辑
    [self forceToOrientation:UIDeviceOrientationPortrait];
    [[UIApplication sharedApplication] setStatusBarOrientation:UIDeviceOrientationPortrait];
    [self addSubview:self.containerView];
    
    [self.containerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    
    WS(ws);
    [UIView animateWithDuration:.25 animations:^{
        ws.containerView.transform = CGAffineTransformIdentity;
    }];
    */
    self.containerView.backgroundColor = [UIColor clearColor];
    self.bottomBar.isFullScreen = NO;
    self.isFullScreen = NO;
    self.backBtn.hidden = self.showBackBtnInSmallScreen == YES ? NO : YES;
    
    [[UIApplication sharedApplication] setStatusBarHidden:self.statusBarHidden withAnimation:UIStatusBarAnimationNone];
}

#pragma mark - 全屏、半屏核心方法
- (void)forceToOrientation:(UIDeviceOrientation)orientation{
    
    NSNumber *orientationUnknown = [NSNumber numberWithInt:0];
    [[UIDevice currentDevice] setValue:orientationUnknown forKey:@"orientation"];
    
    NSNumber *orientationTarget = [NSNumber numberWithInt:orientation];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}


#pragma mark - 监听前台后台的逻辑
/** 即将显示 */
-(void)appWillEnterForeground:(NSNotification*)note {
    if (self.isFullScreen) {
        [self smallScreen];
    }
}
/** 即将隐藏 */
-(void)appwillResignActive:(NSNotification *)note {
    if (self.state == TLPlayerStatePlaying) {
        [self pause];
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    NSLog(@"-----%s",__FUNCTION__);
}
@end
